<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">收料</block>
		</cu-custom>
		<form>
			<view style="line-height: 40px;margin-top: 10px;">
				<radio-group @change="radioChange">
					<view class="scroll-row" v-for="(item, index) in suppliers" :key="item.value">
						<radio :value="item.value" :checked="item.checked" style="transform:scale(0.7);margin-left: 10px;" />
						<span>{{item.text}}</span>
					</view>
				</radio-group>
			</view>
			<view class="cu-form-group">
				<view class="title">工单号输入</view>
				<input placeholder="请输入工单号" disabled="true" name="input" v-model="myFormData.workOrderNumber"></input>
			    <button v-if="itemChilds.length>0" class="cu-btn bg-yellow lg" @click="openSubOrder" >子工单</button>
			</view>
			<view class="cu-form-group">
				<view class="title">工艺名称</view>
				<view class="action" style="width: 60%;margin-right: 60px;">
					<uni-data-select :disabled="empProcess" v-model="myFormData.id"
						style="font-size: 12px;height: 30px;" :localdata="range" @change="change"></uni-data-select>
				</view>
			</view>
<!-- 			<view class="cu-form-group">
				<view class="title">客户料号</view>
				<view class="action">
					<text class="text-grey">{{myFormData.custCode}}</text>
				</view>
			</view> -->
<!-- 			<view class="cu-form-group">
				<view class="title">产品名称</view>
				<view class="action">
					<text class="text-grey">{{myFormData.name}}</text>
				</view>
			</view> -->
<!-- 			<view class="cu-form-group">
				<view class="title">工单数量</view>
				<view class="action">
					<text class="text-grey">{{myFormData.qtyWorkOrder}}</text>
				</view>
			</view> -->
			
			<view class="cu-form-group">
				<view class="title" style="width:200px;">未收数量</view>				
				<view class="action" style="width:222px;">
					<text class="text-grey">{{myFormData.balanceQty==null?0:myFormData.balanceQty}}</text>
				</view>
				<view style="width:300px;">
					<button v-if="queryAbnVisual" class="cu-btn bg-gradual-orange lg" @click="queryAbn" >异常记录</button>
				</view>		
			</view>
			<view class="cu-form-group">
				<view class="title" >送货单号码</view>				
				<input placeholder="输入送货单号码" name="input" v-model="myFormData.referenceDocNo"></input>
			</view>
<!-- 			<view style="line-height: 60px;margin-top: 0px;margin-bottom: -10px;">
				<scroll-view  scroll-x >
					<checkbox-group @change="checkboxChange" placement="row">
						<label class="uni-list-cell uni-list-cell-pd" v-for="item in opItems[selectedSupplierId]" :key="item.id">					
								<checkbox :value="item.id" :checked="item.checked"  style="transform:scale(0.7);margin-top: 4px;margin-left: 10px;"/>
								<span>工序:{{item.processName}}</span>
								<span>数量:{{item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0)}}</span>
								<span style="position:relative;top:-38rpx;margin-left:-60px;">{{item.outsourceNo}}</span>
						</label>
					</checkbox-group>
				</scroll-view>
			</view> -->
						<view style="line-height: 40px;margin-top: 10px;margin-bottom: 10px;">
							<scroll-view class="scroll-view_H" scroll-x="true" @scroll="scroll" scroll-left="120">
<!-- 								<radio-group @change="checkboxChange" placement="row">
									<view class="scroll-row" v-for="item in opItems[selectedSupplierId]" :key="item.id">					
											<checkbox style="transform: scale(0.7);" :value="item.id" :checked="item.checked" />
											<span class="scroll-view-item_H">工序:{{item.processName}}</span>
											<span class="scroll-view-item_H">数量:{{item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0)}}</span>
											<span class="scroll-view-item_H">{{item.outsourceNo}}</span>
									</view>
								</radio-group> -->
								<uni-data-checkbox multiple v-model="checkbox1"  @change="checkBoxChange1" :localdata="rangeValue"></uni-data-checkbox>
							</scroll-view>
						</view>
			<view class="cu-form-group">
				<view class="title" style="font-size: 42rpx;">收货数量</view>
				<input ref="inputName" :focus="focusState" type="number" placeholder="输入收货数量" name="input" v-model="myFormData.qty" @input="changeQty(1)"></input>
			</view>
			<view class="cu-form-group container-btn ">
				<button class="cu-btn bg-blue lg" @click="scanApp">继续扫</button>
			</view>
<!-- 			<view>
				<uni-fab :pattern="pattern" :horizontal="horizontal" :vertical="vertical" :direction="direction"
					@fabClick="scan"></uni-fab>
			</view> -->
		</form>
		<view style="margin-top: 10px;">
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="20" align="center">序号</uni-th>
					<uni-th width="150" align="center">供应商</uni-th>
					<uni-th width="150" align="center">客户料号</uni-th>
					<uni-th width="150" align="center">产品名称</uni-th>
					<uni-th width="150" align="center">工序</uni-th>
					<uni-th align="center">数量</uni-th>
					<uni-th align="center">备注</uni-th>
					<uni-th width="204" align="center">设置</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td align="center">{{ index + 1 }}</uni-td>
					<uni-td align="center">{{ item.supplierName }}</uni-td>
					<uni-td align="center">{{ item.custCode }}</uni-td>
					<uni-td align="center">{{ item.name }}</uni-td>
					<uni-td align="center">
						<view class="name">{{ item.processId_dictText }}</view>
					</uni-td>
					<uni-td align="center">{{ item.qty }}</uni-td>
					<uni-td align="center">
						
						<input placeholder="请输入备注" name="input" v-model="item.remark"></input>
					</uni-td>
					<uni-td>
						<view class="uni-group">
							<!-- <button class="uni-button" size="mini" type="primary">修改</button> -->
							<button class="uni-button" size="mini" @tap="delTable(row)" type="warn">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<view class="cu-form-group container-btn ">
			<button class="cu-btn bg-blue lg" @click="onSubmit(0)">提交</button>
			<!-- <button class="cu-btn bg-green lg" @click="()=>{}" style="margin-left: 10px;">打印</button> -->
		</view>
		<view class="cu-form-group">
		</view>
		
<view class="example-body">
				<drawer :show="subOrderDrawerShow" @cancel="subOrderCancel" @ensure="subOrderEnsure" >
				<!--            <view>右往左滑动</view>
				            <view>自定义内容</view>		 -->	
							<view style="margin-top: 140rpx;">
							<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据" @selection-change="selectionChange">
								<uni-tr>
									<uni-th width="50" align="center">序号</uni-th>		
									<uni-th width="150" align="center">工单号</uni-th>
									<uni-th width="150" align="center">客户</uni-th>
									<uni-th width="120" align="center">产品编码</uni-th>
									<uni-th width="150" align="center">客户料号</uni-th>
									<uni-th width="120" align="center">图号</uni-th>
								    <uni-th width="120" align="center">产品名称</uni-th>
									<uni-th width="150" align="center">版本</uni-th>
									<uni-th width="120" align="center">数量</uni-th>
									<uni-th width="120" align="center">下单日期</uni-th>	
								    <uni-th width="120" align="center">需求日期</uni-th>									
								</uni-tr>
								<uni-tr v-for="(item, index) in itemChilds" :key="index">
									<uni-td>{{ (index + 1) }}</uni-td>
									<uni-td>{{ item.workOrderNumber }}</uni-td>
									<uni-td>{{ item.customerShortName }}</uni-td>
									<uni-td>{{ item.code }}			</uni-td>
									<uni-td>		{{item.custCode}}		</uni-td>
                                    <uni-td>		{{item.drawingNo}}		</uni-td>
									<uni-td>		{{item.name}}		</uni-td>
									<uni-td>		{{item.productVer}}		</uni-td>
									<uni-td>		{{item.qty}}		</uni-td>
									<uni-td>		{{item.orderDate ? item.orderDate : '' }}		</uni-td>
									<uni-td>		{{item.deliveryDate ? item.deliveryDate : '' }}		</uni-td>
								</uni-tr>
							</uni-table>
							<view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="changePage" /></view>
				            </view>
						</drawer>	
			</view>			
		
		
		<view class="example-body">
		        <drawer :show="drawerShow" @cancel="cancel" @ensure="ensure" >
		<!--            <view>右往左滑动</view>
		            <view>自定义内容</view>		 -->	
					<view style="margin-top: 140rpx;">
					<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据" @selection-change="selectionChange">
						<uni-tr>
							<uni-th width="50" align="center">序号</uni-th>					
							<uni-th width="150" align="center">客户料号</uni-th>
							<uni-th width="120" align="center">日期</uni-th>
							<uni-th width="150" align="center">问题描述</uni-th>
							<uni-th width="120" align="center">不良图片</uni-th>
							
		<!-- 					<uni-th align="center">地址</uni-th>
							<uni-th width="204" align="center">设置</uni-th> -->
						</uni-tr>
						<uni-tr v-for="(item, index) in abnTableData" :key="index">
							<uni-td>{{ (index + 1) }}</uni-td>
							<uni-td>{{ item.custCode }}</uni-td>
							<uni-td>{{ item.samplingDate }}</uni-td>
							<uni-td>
								<view @click="open(item.abnormalDescription)" class="name">{{ item.abnormalDescription ? item.abnormalDescription: ""}}</view>
							</uni-td>
							<uni-td>
								<view>
								    <image
								      class="image"
								      :src="getImage(item)"
								      @click="previewImage($event,item,index)"							  
								    ></image>
								  </view>
							</uni-td>
							<!-- <uni-td align="center">{{ item.address }}</uni-td> -->
		<!-- 					<uni-td>
								<view class="uni-group">
									<button class="uni-button" size="mini" type="primary">修改</button>
									<button class="uni-button" size="mini" type="warn">删除</button>
								</view>
							</uni-td> -->
						</uni-tr>
					</uni-table>
					<view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="changePage" /></view>
		            </view>
				</drawer>	
				</view>		
		<!-- <view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="change" /></view> -->
	</view>
</template>

<script>
	import api from '@/api/api.js'
	import {
		USER_INFO
	} from "@/common/util/constants"
	import {
		forEach
	} from "../../common/luch-request/utils";
    import {scanCode } from "@/uni_modules/lime-scan"  	
	export default {
		name: 'receiveOpmProcessQty',
		data() {
			return {
				items: [{
						value: 'USA',
						name: '美国'
					},
					{
						value: 'CHN',
						name: '中国',
						checked: 'true'
					},
					{
						value: 'BRA',
						name: '巴西'
					},
					{
						value: 'JPN',
						name: '日本'
					},
					{
						value: 'ENG',
						name: '英国'
					},
					{
						value: 'FRA',
						name: '法国'
					},
					{
						value: 'JPN',
						name: '日本'
					},
					{
						value: 'ENG',
						name: '英国'
					},
					{
						value: 'FRA',
						name: '法国'
					}
				],
				checkbox1: [],
				rangeValue: [],
				index: -1,
				switchC: true,
				empProcess: false,
				imgList: [],
				opItems:[],
				range: [],
				suppliers: [],
				
				itemChilds : [],
				createQrcodeInCad : false,
				subOrderDrawerShow:false,
				
				selectedSupplierId : '',
				uploadUrl: "/sys/common/upload",
				processIds: '',
				workprocess: null,
				userInfo: null,
				abnTableData:[],
				focusState:false,
				queryAbnVisual:false,
				drawerShow:false,				
				myFormData: {
					// woQty: 10,
					// custCode: '',
					// name: '',
					// productVer: '',
					// employee: '',
					// employeeId: '',
					// workOrderNumber: '',
					// avatar: '',
					// realname: '',
					// username: '',
					// sex: 1,
					// birthday: '',
					// orgCode: '',
					// workNo: '',
					// phone: '',
					// email: '',
					// id: '',
					customerAddress: '',
					contacts: '',
					customerTell : '',
					outsourceNo: '',
				},
				outsourceNo:'',
				title: 'uni-fab',
				directionStr: '垂直',
				horizontal: 'right',
				vertical: 'top',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff',
					icon: 'scan'
				},
				is_color_type: false,
				content: [{
						iconPath: '/static/image.png',
						selectedIconPath: '/static/image-active.png',
						text: '相册',
						active: false
					},
					{
						iconPath: '/static/home.png',
						selectedIconPath: '/static/home-active.png',
						text: '首页',
						active: false
					},
					{
						iconPath: '/static/star.png',
						selectedIconPath: '/static/star-active.png',
						text: '收藏',
						active: false
					}
				],
				customNumberConfig: {
					ruleField: 'dnNumber',
					ruleCode: 'out_dn_number', //pom_delivery_note_no
					ruleName: '采购收货单编码',
					ruleUrl: '/sys/fillRule/executeRuleByCode/',
				},
				searchVal: '',
				tableData: [],
				saveHeaderData:{},
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				loading: false,
				totalWorkProcessQty : 0,
			    selectedOpProcessIds : [],
				selectedOpItemsRecord : {},
				url:{
					querySupplierDefaultById: '/bas/basSupplier/default',
				},
				scrollTop: 0,
				old: {
					scrollTop: 0
				}
			};
		},
		onLoad: function(option) {
			// this.getEmployee()
			this.selectedIndexs = []
		},
		created() {
			this.userInfo = uni.getStorageSync(USER_INFO)
			this.myFormData.employee = this.userInfo.username
			this.myFormData.employeeId = this.userInfo.id
			// this.getEmployee()
			// this.getSuppliers();
			this.getCustomNumber()
			// this.scan()
			// this.tableData = this.getData()
			console.log(this.userInfo)
		},
		methods: {
			checkBoxChange1(e){
				console.log('e:',e);
				if (e.detail.value) {
					e.detail.value.forEach((u)=>{
						this.getCheckBoxData(u)
					})
				}
			},
			changePage(e) {
				// this.$refs.table.clearSelection()
				// this.selectedIndexs.length = 0
				// this.getOrderData(e.current)
			},
			openSubOrder(){
				this.subOrderDrawerShow = true
			},				
			getImage(record) {
				if (record.attachment) {
					return api.getFileAccessHttpUrl(record.attachment.split(',')[0])
				}
			},
			previewImage(e,record,index) {
				// 获取图片列表，这里只有一张图片，可以直接放大
				
				let images = record.attachment.split(',');
				let _images = []
				images.forEach((v)=>{
					_images.push( api.getFileAccessHttpUrl(v)	)
				})
				// 调用uni.previewImage方法进行预览
				uni.previewImage({
				  current: _images[0], // 当前显示图片的http链接
				  urls: _images // 需要预览的图片http链接列表
				});
			  },	
			//取消
			cancel() {
			    console.log('您点击了取消按钮')
			    this.drawerShow = false;
			},			
			//确定
			ensure(){
			    console.log('您点击了确定按钮')
			    this.drawerShow = false;
			},	
				subOrderCancel() {
				    console.log('您点击了取消按钮')
				    this.subOrderDrawerShow = false;
				},
				//确定
				subOrderEnsure(){
				    console.log('您点击了确定按钮')
				    this.subOrderDrawerShow = false;
				},			
			queryAbn(){
				this.drawerShow = true
			},			
			upper: function(e) {
				console.log(e)
			},
			lower: function(e) {
				console.log(e)
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon:"none",
					title:"纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			getCheckBoxData(u) {
				this.totalWorkProcessQty = 0
				this.selectedOpProcessIds = []
				this.selectedOpItemsRecord = {}
				this.opItems[this.selectedSupplierId].forEach((item)=>{
					// e.detail.value.forEach((u)=>{
				
					// })
					// let u = e.detail.value
					if (item.id == u) {
						let _qty = item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0)
						this.totalWorkProcessQty = this.totalWorkProcessQty + _qty
						this.selectedOpProcessIds.push(u)		
						this.selectedOpItemsRecord = item
					}
				})
				this.myFormData.qty = this.totalWorkProcessQty 
				if (this.myFormData.qty > 0) {
					this.changeQty(2)
				}
			},
			checkboxChange: function (e) {
				console.log(e)
				this.totalWorkProcessQty = 0
				this.selectedOpProcessIds = []
				this.selectedOpItemsRecord = {}
				this.opItems[this.selectedSupplierId].forEach((item)=>{
					// e.detail.value.forEach((u)=>{

					// })
					let u = e.detail.value
					if (item.id == u) {
						let _qty = item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0)
						this.totalWorkProcessQty = this.totalWorkProcessQty + _qty
						this.selectedOpProcessIds.push(u)		
						this.selectedOpItemsRecord = item
					}
				})
				this.myFormData.qty = this.totalWorkProcessQty 
				if (this.myFormData.qty > 0) {
					this.changeQty(2)
				}
			},
			radioChange(evt) {
				console.log(evt)
				this.selectedSupplierId = evt.detail.value
				this.myFormData.supplierId = evt.detail.value
				this.myFormData.qty = null
				this.tableData = []
				this.suppliers.find((item)=>{
					if (item.value == this.selectedSupplierId) {
						this.myFormData.supplierName = item.text
					}
				})
				
				this.rangeValue = [];				
				if (this.opItems[this.selectedSupplierId]) {
					this.opItems[this.selectedSupplierId].forEach((item)=>{
						let rangeObj = {}
						let _qty = item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0) + 0
						let _text = '工序: ' + item.processName + ' 数量: ' + _qty + ' ' + item.outsourceNo
						rangeObj.text = _text
						rangeObj.value = item.id
						this.rangeValue.push(rangeObj);
					})
				}
			},
			setFocus() {
				let that = this
				this.$nextTick(()=>{
					setTimeout(() => {
								that.focusState = true
						},1000)
				})
			},
			changeSupp(val) {
				let that = this
				this.$http.get(
					this.url.querySupplierDefaultById + '/' + val, {
						params: {}
					}
				).then((res) => {
				          if (res.data.result.basSupplierAddress) {
				            that.myFormData.customerAddress = res.data.result.basSupplierAddress.address
				          }
				          if (res.data.result.basSupplierContacts) {
				            that.myFormData.contacts = res.data.result.basSupplierContacts.contacts
				            that.myFormData.customerTell = res.data.result.basSupplierContacts.mobilePhone
				          }
				});
			},		
				
			changeQty(e) {
				console.log(e)
				if (!this.myFormData) return
				if (!this.myFormData.qty || this.myFormData.qty == 0) return
				let checkFlag = false
				this.tableData.forEach((item)=>{
					if (item.supplierId != this.myFormData.supplierId) {
						checkFlag = true
					}
				})
				if (checkFlag) {
					this.$tip.alert("供应商不同，不能添加！") 
					return
				}
				//防止扫不同的供应商
                if (!this.tableData || this.tableData.length == 0) {
					let obj = Object.assign({},this.myFormData)
					this.saveHeaderData.autoStock= null
					this.saveHeaderData.contacts= obj.contacts
					this.saveHeaderData.contactsTell= obj.customerTell
					this.saveHeaderData.dnDate= Date.now()
					this.saveHeaderData.dnNumber= this.outsourceNo
					this.saveHeaderData.dnType= "1"
					this.saveHeaderData.referenceDocNo= obj.referenceDocNo			
					this.saveHeaderData.remark= 'DataFromApplication'
					this.saveHeaderData.dataFrom = 'DataFromApplication'
					this.saveHeaderData.status= "2"
					this.saveHeaderData.supplierId= obj.supplierId
				}
				if (this.totalWorkProcessQty == 0) {
					let _total = 0
					this.opItems[this.selectedSupplierId].forEach((item)=>{
						_total = _total + item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0)
					})
					if (this.myFormData.qty > _total) {
						this.$tip.alert("数量超出了工单工序数量总数！")
						return
					}
				} else {
					if (this.myFormData.qty > this.totalWorkProcessQty) {
						this.$tip.alert("数量超出了选择工单工序数量！")
						return
					}
				}			
				let that = this;
				if (this.selectedOpItemsRecord) {
					let qtyReceipt = this.selectedOpItemsRecord.qtyReceipt ? this.selectedOpItemsRecord.qtyReceipt : 0
					let qtyReturn = this.selectedOpItemsRecord.qtyReturn ? this.selectedOpItemsRecord.qtyReturn : 0
					let qty = this.selectedOpItemsRecord.qty
					let qtyBalance = qty - qtyReceipt + qtyReturn
					if (this.tableData.length == 0) {
						let obj = Object.assign({},this.selectedOpItemsRecord)
						obj.selectedOpProcessIds = this.selectedOpProcessIds
						obj.qty = qtyBalance
						this.tableData.push(obj)
					} else {
						let flag = false
						this.tableData.forEach((item)=>{
							 if (item.id == that.selectedOpItemsRecord.id) {
								 flag = true
								 if (e == 1) {
									item.qty = that.myFormData.qty
								 }
								 // item.selectedOpProcessIds = this.selectedOpProcessIds
							 }
						})
						if (!flag) {
							let obj = Object.assign({},this.selectedOpItemsRecord)
							obj.selectedOpProcessIds = this.selectedOpProcessIds
							obj.qty = qtyBalance
							this.tableData.push(obj)
						}
					}
				}
			},
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i])
			},
			// 多选
			selectionChange(e) {
				console.log(e.detail.index)
				this.selectedIndexs = e.detail.index
			},
			//批量删除
			delTable(index) {
				this.selectedIndexs.forEach((u)=>{
					console.log(u)
					this.tableData.splice(u,1)		
				})
				this.$refs.table.clearSelection()
			},
			getCustomNumber() {
				this.$http.put(
					this.customNumberConfig.ruleUrl + this.customNumberConfig.ruleCode, {
						params: this.myFormData
					}
				).then((res) => {
					// 执行成功，获取返回的值，并赋到页面上
					if (res.data && res.data.result) {
						this.outsourceNo = res.data.result;
					}
				});
			},
			getSuppliers() {
				console.log("beging find supplier.")
				this.$http.get(
					"/bas/basSupplier/list", {
						params: {
							pageSize: 1000
						}
					}).then(res => {
					console.log("res::supplier>", res)
					if (res.data.result.records) {
						let data = res.data.result.records
						this.suppliers = []
						data.forEach((item) => {
							let obj = {
								value: item.id,
								text: item.name
							}
							this.suppliers.push(obj)
						})
					}
				})
			},
			getEmployee() {
				this.processIds = ''
				console.log("beging find employee.")
				this.$http.get("/bas/basEmployee/list", {
					params: {
						code: this.userInfo.username
					}
				}).then(res => {
					console.log("res::employee>", res)
					if (res.data.result.records[0]) {
						this.processIds = res.data.result.records[0].processIds
					}
				})
			},
			scanApp() {
				let that = this
				this.focusState = false
				scanCode({
					params: '{"showVibrate": true,"showBeep": true,"showPhotoAlbum": true,"showLightController": true,"supportZoom": true,"scanColor": "#ff0000","fullScreenScan":true}',  
					success: (res) => {  
						const innerAudioContext = uni.createInnerAudioContext();
																		innerAudioContext.autoplay = true;
																		innerAudioContext.src = 'https://www.suzi-info.com/13193.wav';  //音频地址
																		innerAudioContext.onPlay(() => {
																			console.log('开始播放');
																		});
																		innerAudioContext.onError((res) => {
																		  console.log(res.errMsg);
																		  console.log(res.errCode);
																		});
																		
						let obj = res
						// let obj = JSON.parse(res)
						if (obj.errMsg == 'ok') {
							let scanResults = obj.result
							let scanDataRes = scanResults?.split('/')
							
							if (that.createQrcodeInCad && that.itemChilds.length>0 &&  scanDataRes && scanDataRes.length == 5) {
								if (scanDataRes[4] == "salseorder") {
									that.myFormData.workOrderNumber = scanDataRes[3]
									that.getWorkOrderData("salseorder");
								} else {
									let data = that.findWorkOrderNo(scanDataRes[0])
									console.log(data)
									if (data && data.length>0) {
										that.myFormData.workOrderNumber = data[0].workOrderNumber
										that.repeatPrint = false					
										that.getWorkOrderData();
									} else {
										that.notFindWorkOrderNo()
									}
								}
							} else {
								if (scanDataRes && scanDataRes.length == 5) {
									if (scanDataRes[4] == "salseorder") {
										that.myFormData.workOrderNumber = scanDataRes[3]
										that.getWorkOrderData("salseorder");
									} else {
										that.notFindWorkOrderNo()
									}
								} else {
									that.myFormData.workOrderNumber = scanDataRes[0] //res.result.split('/')[0]
									that.getWorkOrderData();
								}
							}
						}
					}
				});	
			},
			scan() {
				this.focusState = false
				let that = this
				console.log("进来了")
				// #ifndef H5
				uni.scanCode({
					success: function(res) {
									  const innerAudioContext = uni.createInnerAudioContext();
												innerAudioContext.autoplay = true;
												innerAudioContext.src = 'https://www.suzi-info.com/13193.wav';  //音频地址
												innerAudioContext.onPlay(() => {
													console.log('开始播放');
												});
												innerAudioContext.onError((res) => {
												  console.log(res.errMsg);
												  console.log(res.errCode);
												});
												
						let scanDataRes = res.result.split('/')
						if (that.createQrcodeInCad && that.itemChilds.length>0 &&  scanDataRes && scanDataRes.length == 5) {
							if (scanDataRes[4] == "salseorder") {
								that.myFormData.workOrderNumber = scanDataRes[3]
								that.getWorkOrderData("salseorder");
							} else {
								let data = that.findWorkOrderNo(scanDataRes[0])
								console.log(data)
								if (data && data.length>0) {
									that.myFormData.workOrderNumber = data[0].workOrderNumber
									that.repeatPrint = false					
									that.getWorkOrderData();
								} else {
									that.notFindWorkOrderNo()
								}
							}
						} else {
							if (scanDataRes && scanDataRes.length == 5) {
								if (scanDataRes[4] == "salseorder") {
									that.myFormData.workOrderNumber = scanDataRes[3]
									that.getWorkOrderData("salseorder");
								} else {
									that.notFindWorkOrderNo()
								}
							} else {
								that.myFormData.workOrderNumber = res.result.split('/')[0]
								that.getWorkOrderData();
							}
						}						
						/////	2025-3-12					
						// that.myFormData.workOrderNumber = res.result.split('/')[0]
						// that.getWorkOrderData();
						////
					}
				});
				// #endif
				// #ifdef H5
				this.$tip.alert("暂不支持")
				// #endif
			},
			findWorkOrderNo(code){
				let data = this.itemChilds.filter(item=>item.code == code)
				return data
			},
			notFindWorkOrderNo() {
				this.$tip.toast('没找到子工单数据')
				this.itemChilds = []
				this.createQrcodeInCad = false
				this.myFormData = {}
				this.tableData = []
				this.saveHeaderData = {}
				this.processList = []
				this.range = []
				this.suppliers = []
				this.opItems = []
			},
			changePage() {
				
			},
			change(val) {
				this.myFormData.balanceQty = this.workprocess[val].balanceQty
			},
			getWorkOrderData(scanType) {
				let that = this
				
				this.itemChilds = []
				this.createQrcodeInCad = false
				
				if (!this.myFormData.workOrderNumber) {
					this.$tip.alert('请输入工单号码！');
					
					return false
				}
				let _supplierId = this.myFormData.supplierId
				if (!_supplierId) {
					_supplierId ="畿"
				}
				let param = {
					workOrderNumber: this.myFormData.workOrderNumber,
					supplierId:_supplierId,
					scanType:scanType,
				}
				this.$http.get("/wom/womWorkOrder/getProcessProgressByNo", {
					params: param
				}).then(res => {
					if (res.data.success) {
						let data = res.data.result.allProcessList
						this.opItems = res.data.result.opItems
						let sups = res.data.result.basSuppliers
						console.log((sups))
						this.suppliers = []
						if (sups && sups.length > 0) {
							sups.forEach((item)=>{
								let obj = {
									value: item.id,
									text: item.shortName,
									checked : false							
								}
								this.suppliers.push(obj)
							})
							this.suppliers[0].checked = true
							this.selectedSupplierId = this.suppliers[0].value
							this.rangeValue = [];
							if (this.opItems[this.selectedSupplierId]) {
								this.opItems[this.selectedSupplierId].forEach((item)=>{
									let rangeObj = {}
									let _qty = item.qty - (item.qtyReceipt  ? item.qtyReceipt :0) + (item.qtyReturn?item.qtyReturn:0) + 0
									let _text = '工序: ' + item.processName + ' 数量: ' + _qty + ' ' + item.outsourceNo
									rangeObj.text = _text
									rangeObj.value = item.id
									this.rangeValue.push(rangeObj);
								})
							}
						}

						console.log(this.opItems)
						console.log("res::workOrderNumber list>", data)
						if (data && data.length > 0) {
							if (scanType && scanType == "salseorder") {
								this.myFormData.workOrderNumber = data[0].workOrderNumber
							}
							if (data[0].itemChilds && data[0].itemChilds.length>0 && data[0].createQrcodeInCad ) {
								this.itemChilds = data[0].itemChilds;
								this.createQrcodeInCad = data[0].createQrcodeInCad
							}
							if (data[0].abnProductionAbnormalPageList && data[0].abnProductionAbnormalPageList.length >0) {
								this.abnTableData = data[0].abnProductionAbnormalPageList
								this.queryAbnVisual = true
								this.abnTableData.forEach((item,index)=>{
									if (item.attachment) {
										let url = api.getFileAccessHttpUrl((item.attachment).split(',')[0])
										console.log(url)
									}								
								})
							}
							this.processList = []
							// this.myFormData.woQty = data[0].qtyWorkOrder
							// this.myFormData.custCode = data[0].custCode
							// this.myFormData.name = data[0].name
							// this.myFormData.productVer = data[0].productVer
							// this.myFormData.employee = this.userInfo.username						
							this.workprocess = {}						
							data.forEach((item) => {
								item.workOrderProcessId = item.id
								item.processId_dictText = item.processName
								item.balanceQty = (item.qtyOutIssue == null ? 0 : item.qtyOutIssue) - (item.qtyOutReceive == null ? 0:item.qtyOutReceive)
								item.unitPrice = 1
								let obj = {
									value: item.id,
									text: item.processId_dictText
								}
								this.workprocess[item.id] = item
								if (item.processAttribute && item.processAttribute == 2) {
									this.processList.push(obj)								
								}
							})
							console.log(this.workprocess)
							this.range = this.processList		
							if (this.processList.length == 0) {
								this.$tip.toast('未找到外发工序！')
								return
							}
							// this.myFormData.id = this.processList[0].value
							this.myFormData = Object.assign({},this.workprocess[this.processList[0].value]);
							this.myFormData.outsourceNo = this.outsourceNo
							this.myFormData.qty = null
							this.myFormData.supplierId = this.selectedSupplierId
							this.myFormData.supplierName = this.suppliers.length>0 ? this.suppliers[0].text : ''
							console.log("this.myFormData:" , this.myFormData)
							this.setFocus()
						} else {
							
						}
					} else {
						this.$tip.toast(res.data.message)
					}				
					
				})
			},
			onSubmit(status) {
				let myForm = this.myFormData
				//  let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
				//  let checkEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
				//  console.log("myForm",myForm)
				if (this.tableData.length == 0) {
					this.$tip.alert('没有保存的数据！');
					return false
				}
				if (!this.myFormData.supplierId) {
					this.$tip.alert('请选择供应商！');
					return false
				}
				// if(this.myFormData.balanceQty && this.myFormData.balanceQty>0 && this.myFormData.balanceQty < this.myFormData.qty) {
				// 	this.$tip.toast("数量超出可收货数量！")
				// 	return false
				// }
				// if (this.myFormData.qty > this.totalWorkProcessQty && this.totalWorkProcessQty != 0 ) {
				// 	this.$tip.toast("数量超出选择外协单数量！")
				// 	return false
				// }
				// // if (!this.myFormData.qtyOutIssue || this.myFormData.qtyOutIssue == 0) {
				// 	this.$tip.toast("没有可以收货的数量！") 
				// 	return false
				// }
				

				let flag = false
				this.tableData.forEach((item)=> {
					// item.workOrderProcessId = item.id
					item.selectedOpProcessIds = [item.id]
					delete item.id;
					if(item.balanceQty && item.balanceQty>0 && item.balanceQty < item.qty) {
						flag = true
					}
					if (!item.qtyOutIssue || item.qtyOutIssue == 0) {
						flag = true
					}
				})				
				// if (flag) {
				// 	this.$tip.toast("数量超出可收货数量！")
				// 	return false
				// }
				// let param = {
				// 	autoStock: null,
				// 	contacts: this.myFormData.contacts,
				// 	contactsTell: this.myFormData.customerTell,
				// 	dnDate:  Date.now(),
				// 	dnNumber: this.outsourceNo,
				// 	dnType: "1",
				// 	referenceDocNo: this.myFormData.referenceDocNo,					
				// 	remark: 'DataFromApplication',
				// 	status: "2",
				// 	selectedOpProcessIds:this.selectedOpProcessIds,
				// 	supplierId: this.myFormData.supplierId,
				// 	opmDeliveryNoteItemList: this.tableData,
				// 	opmDeliveryNoteStatusList:[],
				// }		
				let param = Object.assign({},this.saveHeaderData) 
				param.opmDeliveryNoteItemList = this.tableData
				param.opmDeliveryNoteStatusList = []
				param.selectedOpProcessIds = this.selectedOpProcessIds
				console.log(param)
				let messages = ''
				this.$tip.loading();
				this.$http.post('/opm/opmDeliveryNote/add', param).then(res => {
					console.log(res)
					this.$tip.loaded();
					if (res.data.success) {
						this.$tip.toast('提交成功')
						this.myFormData = {}
						this.tableData = []
						this.saveHeaderData = {}
						this.processList = []
						this.range = []
						this.suppliers = []
						this.opItems = []
					} else {
						this.$tip.loaded();
						this.$tip.alert(res.data.message)
						this.tableData = []
						this.saveHeaderData = {}
					}
				}).catch((e) => {
					this.$tip.loaded();
					this.$tip.error('提交失败')
					this.tableData = []
					this.saveHeaderData = {}
				});
			},
			DateChange(e) {
				this.myFormData.birthday = e.detail.value
			},
			SwitchC(e) {
				this.switchC = e.detail.value
			},
			ChooseImage() {
				var that = this;
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						that.$http.upload(that.$config.apiUrl + that.uploadUrl, {
								filePath: res.tempFilePaths[0],
								name: 'file'
							})
							.then(res => {
								that.myFormData.avatar = res.data.message;
							})
							.catch(err => {
								that.$tip.error(err.data.message)
							});
						this.imgList = res.tempFilePaths
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '召唤师',
					content: '确定要删除这段回忆吗？',
					cancelText: '再看看',
					confirmText: '再见',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
		}
	}
</script>

<style>
	.cu-form-group .title {
		font-weight: 600;
		min-width: calc(4em + 15px);
	}

	.button-sp-area {
		margin-left:30%;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		/* margin: 10 auto; */
		/* width: 60%; */
	}
	.scroll-Y {
		height: 300rpx;
	}
	
	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}
	
	.scroll-view-item {
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}
	/* 新增类，设置行间距 */
	.scroll-row {
	  margin-bottom: 20rpx;
	  background-color: #e9e9eb; /* 设置背景颜色为白色 */
	  padding: 10rpx; /* 可以添加一些内边距，让内容不紧贴边缘 */
	}
	.scroll-view-item_H {
		display: inline-block;
		width: 30%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 26rpx;
		  /* 调整字段间的距离 */
		  margin-right: 20rpx; 
	}
	
	.container-btn {
	  display: flex;
	  justify-content: center; /* 水平居中 */
	  align-items: center; /* 垂直居中 */
	  height: 100%; /* 父容器需要有确定的高度 */
	}
	.example-body {
		padding: 10px;
	}
	.image {
	   width: 30px; /* 设置图片宽度 */
	   height: 20px; /* 设置图片高度 */
	 }	
</style>
